/*
 * Copyright (C) 2015 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.example.app;

import android.app.Application;
import android.app.KeyguardManager;
import android.content.Context;
import android.os.PowerManager;
import android.support.test.runner.AndroidJUnitRunner;

// Borrowed from spoon-sample app
// android.permission.DISABLE_KEYGUARD and android.permission.WAKE_LOCK permission is required
public class SpoonInstrumentationTestRunner extends AndroidJUnitRunner {
    @Override
    public void onStart() {
        runOnMainSync(() -> {
            final Application app = (Application) getTargetContext().getApplicationContext();
            final String simpleName = SpoonInstrumentationTestRunner.class.getSimpleName();

            // Unlock the device so that the tests can input keystrokes.
            ((KeyguardManager) app.getSystemService(Context.KEYGUARD_SERVICE))
                    .newKeyguardLock(simpleName)
                    .disableKeyguard();

            // Wake up the screen.
            ((PowerManager) app.getSystemService(Context.POWER_SERVICE))
                    .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager
                            .ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, simpleName)
                    .acquire();
        });

        super.onStart();
    }
}
